<?php
/**
* This file holds a class for AdminController.
* @package busmap
*/

/**
* This class holds AdminController class, that is responsible for all admin actions:
* Showing user level in index, editing/inserting/deleting buslines, busstops and colors.
* @package busmap
*/

class AdminController extends Zend_Controller_Action
{
	protected $userSession;

	/**
	* When initialized, we get the session Auth for authentication
	*/
    public function init(){
        $this->userSession = new Zend_Session_Namespace('Auth');
		if(!$this->userSession->id){
			$this->render('notloggedin');
		}
    }

	/**
	* Index shows logged in user level [level checking not implemented]
	*/
    public function indexAction(){
			$this->view->loggedIn = true;
			$userRightsArray = array(1=>'administraator');
			$this->view->userRightsTxt = $userRightsArray[$this->userSession->level];
    }
	
	/**
	* Function for editing/deleting buslines.
	* Fetches all buslines and corresponding busstops. On each editing, it checks if busstops have been removed from the line.
	* Inserting new busstops is called with Ajax.
	* Deleting a busline occurs when delete_confirm button has been clicked. Deleting sets a delete_time for the corresponding busline.
	*/
    public function editbuslinesAction(){
        $busline = new Application_Model_BusLineMapper();
		$entries = $busline->fetchAll();
        $this->view->entries = $entries;
		if(count($_POST)){
			$buslineForm = new Application_Form_Admin_editBusline();
			$changedBusline = new Application_Model_Busline();

			if($buslineForm->isValid($_POST)){
				
				foreach($entries as $entry){
					$hasMatch = false;
					if($entry->id == $buslineForm->id->getValue()){
						$buslineForm->populateWithBusstops($entry->busstops, $entry->id);
						if($buslineForm->busstopsForm->isValid($_POST['busstopsForm'])){
							$hasMatch = true;
							break;
						}
					}
				}
				if($hasMatch){
					if(array_key_exists('change', $_POST)){
						$changedBusline->setId($buslineForm->id->getValue())
								->setName($buslineForm->name->getValue())
								->setDescription($buslineForm->description->getValue())
								->setBusstops($buslineForm->busstopsForm->getValues())
								->setColorId($buslineForm->colorId->getValue())
								;
						$busline->save($changedBusline);
						$this->_redirect('/admin/editBuslines');
					}
					if(array_key_exists('delete_confirm', $_POST)){
						$changedBusline->setId($buslineForm->id->getValue())
								->setDeleteTime(time());
						$busline->save($changedBusline);
						$this->_redirect('/admin/editBuslines');

					}
				}
			}else{
				$this->view->errors = $buslineForm->getMessages();
			}

		}
		if(array_key_exists('addNew', $_POST)){
			$buslineForm = new Application_Form_Admin_insertBusline();
			if($buslineForm->isValid($_POST)){
				$newBusline = new Application_Model_Busline();
				$newBusline->setName($buslineForm->name->getValue())
						->setDescription($buslineForm->description->getValue())
						->setAddTime(time());
				$newId = $busline->save($newBusline);

				if(count($_POST['busstopsForm'])){
					foreach($_POST['busstopsForm'] as $key => $busstop){
						$newBuslineToBusstop = new Application_Model_BusLineToBusStop();
						$newBuslineToBusstop->setBusLineId($newId)
											->setBusStopId($busstop)
											->setTableOrder($key);
						$buslineToBusstopArr[] = $newBuslineToBusstop;
					}
					$buslineToBusstopMapper = new Application_Model_BusLineToBusStopMapper();
					$buslineToBusstopMapper->saveMany($buslineToBusstopArr);
				}

				$this->_redirect('/admin/editBuslines');
			}else{
				if(array_key_exists('busstopsForm', $_POST) && count($_POST['busstopsForm'])){
					$busstopMapper = new Application_Model_busStopMapper();
					foreach($_POST['busstopsForm'] as $busstopId){
						$newBusstop = new Application_Model_busStop();
						$busstopMapper->find($busstopId, $newBusstop);
						$busstops[] = $newBusstop;
					}
					$buslineForm->populateWithBusstops($busstops);
				}
				$this->view->errors = $buslineForm->getMessages();
				$this->view->insertBuslineForm = $buslineForm;
			}
		}
		if(array_key_exists('addNewBusstop', $_POST) && intval($_POST['afterId']) != 0 && intval($_POST['buslineId']) && intval($_POST['newBusstopId'])){
			$this->_helper->layout->disableLayout();

			$afterId = intval($_POST['afterId']);
			$previousBuslineToBusstop = new Application_Model_BusLineToBusStop();
			$buslineToBusstopMapper = new Application_Model_BusLineToBusStopMapper();
			$buslineToBusstopMapper->find($afterId, $previousBuslineToBusstop);

			$buslineToBusstop = new Application_Model_BusLineToBusStop();
			$buslineToBusstop->setBusLineId(intval($_POST['buslineId']))
							->setBusstopId(intval($_POST['newBusstopId']))
							->setBusLineAfterId($afterId);

			$buslineToBusstopMapper->save($buslineToBusstop);
			$this->_redirect('/busstop/success');

			
		}

    }

	/**
	* Function for inserting new buslines. 
	* Inserting busstops for the new busline adds a new entry to the busstopsForm subform.
	*/
    public function newbuslineAction(){
        $this->_helper->layout->disableLayout();
		$insertBuslineForm = new Application_Form_Admin_insertBusline();
		$busstops = array();

		if(array_key_exists('afterId', $_POST)){
			$afterId = intval($_POST['afterId']);
		}

		if(array_key_exists('addNewBusstop', $_POST)){
			$newBusstop = new Application_Model_Busstop();
			$buslineToBusstopMapper = new Application_Model_busStopMapper();
			$buslineToBusstopMapper->find($_POST['newBusstopId'], $newBusstop);
			if($afterId == -1){
				$busstops[] = $newBusstop;
			}
		}

		if(array_key_exists('busstopsForm', $_POST)){ //Populate with existsing busstops
			foreach($_POST['busstopsForm'] as $key => $busstopEntry){
				$oldBusstop = new Application_Model_Busstop();
				$buslineToBusstopMapper = new Application_Model_busStopMapper();
				$buslineToBusstopMapper->find($busstopEntry, $oldBusstop);
				$busstops[] = $oldBusstop;
				if(($afterId-1)==$key){
					$busstops[] = $newBusstop;
					$newBusstop = false;
				}
			}
			if(!$newBusstop){
				$busstops[] = $newBusstop;
			}
		}

		if(array_key_exists('updateForm', $_POST)){
			$buslineForm = new Application_Form_Admin_insertBusline();
			$insertBuslineForm->populate($_POST);

		}

		$insertBuslineForm->populateWithBusstops($busstops);

		$this->view->insertBuslineForm = $insertBuslineForm;

    }

	/**
	* Function for editing busstops. 
	* Basic function that only allows inserting, deleting and changing busstops.
	* Although bus lines going through the bus stop are also shown, they can't be edited.
	*/
    public function editbusstopsAction(){
        $busstopMapper = new Application_Model_BusStopMapper();
        $this->view->entries =  $busstopMapper->fetchAll();

		$insertBusstopForm = new Application_Form_Admin_insertBusstop();
		if(array_key_exists('addNew', $_POST)){
			
			if($insertBusstopForm->isValid($_POST)){
				$newBusstop = new Application_Model_Busstop();
				$newBusstop->setName($insertBusstopForm->name->getValue())
						->setXCoordinate($insertBusstopForm->xCoordinate->getValue())
						->setYCoordinate($insertBusstopForm->yCoordinate->getValue());

				$busstopMapper->save($newBusstop);

				$this->_redirect('/admin/editBusstops');
			}else{
				$this->view->errors = $insertBusstopForm->getMessages();
			}
		}

		$changeBusstopForm = new Application_Form_Admin_editBusstop();
		if($changeBusstopForm->isValid($_POST)){
			$changeBusstopForm->populate($_POST);
			$changedBusstop = new Application_Model_Busstop();

			if(array_key_exists('delete_confirm', $_POST)){
				$changedBusstop->setId($changeBusstopForm->id->getValue())
						->setName($changeBusstopForm->name->getValue())
						->setXCoordinate($changeBusstopForm->xCoordinate->getValue())
						->setYCoordinate($changeBusstopForm->yCoordinate->getValue())
						->setDeleteTime(time());
				$busstopMapper->save($changedBusstop);
				$this->_redirect('/admin/editBusstops');

			}
			if(array_key_exists('change', $_POST)){
				$changedBusstop->setId($changeBusstopForm->id->getValue())
						->setName($changeBusstopForm->name->getValue())
						->setXCoordinate($changeBusstopForm->xCoordinate->getValue())
						->setYCoordinate($changeBusstopForm->yCoordinate->getValue());
				$busstopMapper->save($changedBusstop);
				$this->_redirect('/admin/editBusstops');
			}
		}else{
			$this->view->changeBusstopFormErrors = $changeBusstopForm->getMessages();
		}
		$this->view->changeBusstopForm = $changeBusstopForm;

		$this->view->insertBusstopForm = $insertBusstopForm;
    }

	/*
	* Function that shows registered users.
	*/
    public function editusersAction(){
        $user = new Application_Model_UserMapper();
        $this->view->entries = $user->fetchAll();
    }

	/*
	* Function that allows deleting, editing and inserting of colors.
	*/
    public function editcolorsAction(){
		
        $colors = new Application_Model_ColorMapper();
		$this->view->entries = $colors->fetchAll();

		$changeColorForm = new Application_Form_Admin_editColor();
		if($changeColorForm->isValid($_POST)){
			$changeColorForm->populate($_POST);

			if(array_key_exists('delete_confirm', $_POST)){
				if($id = $changeColorForm->id->getValue()){
					$colors->deleteEntry($id);
					$this->_redirect('/admin/editColors');
				}
			}
			if(array_key_exists('change', $_POST)){
					$color = new Application_Model_Color();
					$colorMapper = new Application_Model_colorMapper();
					$colorMapper->find($changeColorForm->id, $color);

					$color->setId($changeColorForm->id->getValue())
							->setName($changeColorForm->name->getValue())
							->setRedValue($changeColorForm->redValue->getValue())
							->setGreenValue($changeColorForm->greenValue->getValue())
							->setBlueValue($changeColorForm->blueValue->getValue());
				
					$colorMapper->save($color);
					$this->_redirect('/admin/editColors');
			}
		}else{
			$this->view->changeColorForm = $changeColorForm;
			$this->view->changeColorFormErrors = $changeColorForm->getMessages();
		}
		
		$insertColorForm = new Application_Form_Admin_insertColor();
		if(array_key_exists('addNew', $_POST)){
			
			if($insertColorForm->isValid($_POST)){
				$newColor = new Application_Model_Color();
				$newColor->setName($insertColorForm->name->getValue())
						->setRedValue($insertColorForm->redValue->getValue())
						->setGreenValue($insertColorForm->greenValue->getValue())
						->setBlueValue($insertColorForm->blueValue->getValue());

				$colorMapper = new Application_Model_colorMapper();
				$colorMapper->save($newColor);

				$this->_redirect('/admin/editColors');
			}else{
				$this->view->errors = $insertColorForm->getMessages();
			}
		}

		$this->view->insertColorForm = $insertColorForm;
    }

}

